package com.ssm.interceptor;

import com.ssm.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT认证拦截器
 * 【SpringMVC: 拦截器】
 * 实现HandlerInterceptor接口，用于JWT令牌的验证
 * 【Spring Boot: JWT鉴权】
 * 实现JWT令牌的验证和解析
 */
@Component
public class JwtAuthInterceptor implements HandlerInterceptor {

    /**
     * 【Spring: IOC依赖注入】
     */
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 前置处理方法
     * 【SpringMVC: 拦截器前置处理】
     * 在请求处理之前进行调用，验证JWT令牌
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头中获取Authorization
        String authHeader = request.getHeader("Authorization");
        
        // 如果请求头中没有Authorization，直接返回false
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Unauthorized: No JWT token found");
            return false;
        }

        // 获取JWT令牌
        String token = authHeader.substring(7);
        
        // 验证JWT令牌
        if (!jwtUtil.validateToken(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("Unauthorized: Invalid JWT token");
            return false;
        }

        // 将用户信息存入请求属性中
        request.setAttribute("userId", jwtUtil.getUserIdFromToken(token));
        request.setAttribute("username", jwtUtil.getUsernameFromToken(token));
        request.setAttribute("role", jwtUtil.getRoleFromToken(token));
        
        return true;
    }
} 